package com.tj.jinzao.base;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;

/**
 * 实现LoaderManager Cursor 的fragment，与数据库有交互的基类
 * Created by wjy on 2015/4/24.
 */
public abstract class BaseCursorFragment extends BaseFragment implements LoaderManager.LoaderCallbacks<Cursor> {

    public final static String ARG_LOADER_ID = "loaderId";

    protected int mLoaderId;

    protected Cursor mCursor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLoaderId = getArguments().getInt(ARG_LOADER_ID);
    }

    protected void initLoader() {
        getLoaderManager().initLoader(mLoaderId, null, this);
    }

    public void restartLoader() {
        try {
            getLoaderManager().restartLoader(mLoaderId, null, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
        CursorLoader loader = (CursorLoader) createLoader(id, bundle);
        // Update at most every 300.
        if (loader != null) loader.setUpdateThrottle(300);
        return loader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        if (null != cursor) {
            mCursor = cursor;
            loadFinish(cursor);
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        loadReset();
    }

    abstract protected Loader<Cursor> createLoader(int id, Bundle bundle);

    abstract protected void loadFinish(Cursor cursor);

    abstract protected void loadReset();

}
